import Nerv from "nervjs";

var _this = this;

import { View, ScrollView, Image } from '@tarojs/components';
import './Main.scss';
import Taro, { setStorage as _setStorage } from "@tarojs/taro-h5";
import { request, windowHeight, localHeroData } from '../../../utils';
import { Config } from '../../../Config';
import { AtActivityIndicator, AtBadge } from 'taro-ui';
import HeroIndex from './HeroIndex';
import HeroType from './HeroType';
import pinyin from 'pinyin';
function classify(fn) {
  const res_arr = {};
  this.forEach(item => {
    let classifyKeyword = fn(item);
    if (typeof classifyKeyword !== 'object') {
      classifyKeyword = [classifyKeyword.toString()];
    }
    classifyKeyword.forEach(kw => {
      const s = kw.toString();
      if (res_arr[s] === undefined) {
        res_arr[s] = [];
      }
      res_arr[s].push(item);
    });
  });
  return res_arr;
}
// 以上是数组扩展分类函数
Array.prototype.classify = classify;

class Main extends Taro.Component {
  render() {
    const [heroData, setHeroData] = Taro.useState(localHeroData);
    const [currentKey, setCurrentKey] = Taro.useState('A');
    const [mode, setMode] = Taro.useState('首字母');
    function handleModeChange() {
      setMode(mode === '首字母' ? '职业' : '首字母');
    }
    function handleClickHero(heroEName) {
      Taro.navigateTo({
        url: `/pages/heroDetail/heroDetail?ename=${heroEName}`
      });
    }
    // const [scrollTop, setScrollTop] = useState<number>(0);
    async function getList() {
      let res = await request(Config.获取王者荣耀英雄列表);
      res = res.sort((first, second) => {
        return first.cname.localeCompare(second.cname);
      });
      const classifyResult = res.classify(item => {
        const heroName = item.cname.replace('阿', '啊'); // 因为阿轲的名字的拼音首字母会被识别为e
        const pinyinResult = pinyin(heroName, {
          style: pinyin.STYLE_FIRST_LETTER
        });
        return pinyinResult.length > 0 && pinyinResult[0].length ? pinyinResult[0][0].toUpperCase() : '';
      });
      const classifyResult2 = res.classify(item => item.hero_types);
      const myHeroData = {
        首字母: classifyResult,
        职业: classifyResult2,
        all: { all: res }
      };
      _setStorage({
        key: 'heroData',
        data: myHeroData
      });
      setHeroData(myHeroData);
    }
    Taro.useEffect(() => {
      getList();
    }, []);
    // function handleScroll(e: BaseEventOrig<ScrollViewProps.onScrollDetail>) {
    //   setScrollTop(e.detail.scrollTop);
    // }
    const myCurrentKey = heroData && !heroData[mode][currentKey] ? Object.keys(heroData[mode])[0] : currentKey;
    console.log({ currentKey, myCurrentKey });
    return <View className="Main">
      <ScrollView
      // scrollTop={scrollTop}
      // onScroll={handleScroll}
      className="Main-ScrollView" style={{ height: `${windowHeight}px` }} scrollY>
        {heroData ? heroData[mode][myCurrentKey].map(hero => <View className="Main-ScrollView-Hero" style={{
          backgroundImage: `url(${hero.hero_skin[0].img})`
        }} key={hero.ename} onClick={handleClickHero.bind(this, hero.ename)}>
              <View className="Main-ScrollView-Hero-Left">
                <AtBadge value={hero.new_type === 1 ? '新' : undefined}>
                  <Image className="Main-ScrollView-Hero-Left-HeadIMG" src={hero.hero_img} />
                </AtBadge>
              </View>
              <View className="Main-ScrollView-Hero-Right">
                <View className="Main-ScrollView-Hero-Right-Title">{hero.title}</View>
                <View className="Main-ScrollView-Hero-Right-Name">{hero.cname}</View>
                <HeroType type={mode === '职业' ? Number(myCurrentKey) : hero.hero_types[0]} />
              </View>
            </View>) : <AtActivityIndicator mode="center"></AtActivityIndicator>}
      </ScrollView>
      {heroData && <HeroIndex mode={mode} onModeChange={handleModeChange} current={myCurrentKey} indexes={Object.keys(heroData[mode])} onChange={setCurrentKey} />}
    </View>;
  }

}

export default Main;